
package com.openwater.tools;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;

public class BufferAllocator {

    public static ShortBuffer toShortBuffer(short[] data) {
        ByteBuffer vbb = ByteBuffer.allocateDirect(data.length * 2);
        vbb.order(ByteOrder.nativeOrder());
        ShortBuffer buffer = vbb.asShortBuffer();
        buffer.put(data);
        buffer.position(0);
        return buffer;
    }

    public static IntBuffer toIntBuffer(int[] data) {
        ByteBuffer vbb = ByteBuffer.allocateDirect(data.length * 4);
        vbb.order(ByteOrder.nativeOrder());
        IntBuffer buffer = vbb.asIntBuffer();
        buffer.put(data);
        buffer.position(0);
        return buffer;
    }

    /**
     * put float array to a buffer
     * 
     * @param data
     * @return
     */
    public static FloatBuffer toFloatBuffer(float[] data) {
        ByteBuffer vbb = ByteBuffer.allocateDirect(data.length * 4);
        vbb.order(ByteOrder.nativeOrder());
        FloatBuffer buffer = vbb.asFloatBuffer();
        buffer.put(data);
        buffer.position(0);
        return buffer;
    }

    public static ByteBuffer toByteBuffer(byte[] buffer) {
        ByteBuffer vbb = ByteBuffer.allocateDirect(buffer.length);
        vbb.order(ByteOrder.nativeOrder());
        vbb.put(buffer);
        vbb.position(0);
        return vbb;
    }

}
